package com.iflytek.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iflytek.entity.Answer;
import com.iflytek.entity.Question;
import com.iflytek.service.AnswerService;
import com.iflytek.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;


    @GetMapping("/questionList")
    public String listQuestion(Model model) {
        QueryWrapper<Question> w = new QueryWrapper<Question>().eq("del","0");
        List<Question> questionList = questionService.list(w);
        model.addAttribute("questionList", questionList);
        return "questionList";
    }

    @GetMapping("/questionDetail")
    public String questionDetail(Integer id, Model model) {
        Question question = questionService.getById(id);
        model.addAttribute("q", question);
        System.out.println(question);
        //对应的回答
        List<Answer> answerList = answerService.getAllByQuestionId(question.getId());
        model.addAttribute("answerList", answerList);
        return "questionDetail";
    }

    //跳转到新增问题
    @PostMapping("/questionAdd")
    public String questionAdd() {
        return "questionAdd";
    }

    //保存新增问题
    @PostMapping("/questionSave")
    public String questionSave(Question question, Model model) {
        try {
            questionService.saveQuestion(question);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", e.getMessage());
            return "questionAdd";
        }
        return "redirect:questionList";
    }

    //逻辑删除一个问题
    @GetMapping("/questionMark")
    public String markQuestion(Integer id) {
        questionService.markQuestion(id);
        return "redirect:questionList";
    }

    //前往编辑页面
    @GetMapping("/questionEdit")
    public String editQuestion(Integer id, Model model) {
        Question question = questionService.getById(id);
        model.addAttribute("question", question);
        return "questionEdit";
    }

    //保存修改的信息
    @PostMapping("/questionEditSave")
    public String saveEditQuestion(Question question, Model model) {
        String msg = "保存成功！";
        try {
            questionService.saveEdit(question);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", e.getMessage());
            return "questionEdit";
        }
        model.addAttribute("msg", msg);
        return "questionEdit";
    }


}
